package logic

import (
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	"net/http"
	"tiktok/dao"
	"tiktok/models"
	"tiktok/web"
)

func (p dbregister) TableName() string {
	return "TIKTOK_USER"
}

type registermsg struct {
	models.Status
	Token string `json:"token"` // 用户鉴权token
	Uid   int64  `gorm:"column:uid" json:"user_id"`
}
type dbregister struct {
	models.User
	Password string `gorm:"column:password" json:"password"`
	Token    string `gorm:"column:token" json:"token"`
}

func Register(ctx *gin.Context) {
	username := ctx.Query("username")
	password := ctx.Query("password")
	db := dao.GetDB(ctx)

	p := &dbregister{
		User:     models.User{Name: username},
		Password: password,
	}
	res := db.Create(p)

	if res.Error != nil {
		logrus.Error("插入数据失败")
		ctx.JSON(http.StatusBadRequest, registermsg{
			Status: models.Status{
				StatusCode: -1,
				StatusMsg:  "失败",
			},
		})
	}

	var dbid dbregister
	err := db.Where("name=?", username).Find(&dbid).Error
	if err != nil {
		logrus.Error("select id fail")
	}
	uid := dbid.Uid
	token, err := web.CreateToken(uid, username)
	if err != nil {
		logrus.Error("built token error")
		ctx.JSON(http.StatusBadRequest, registermsg{
			Status: models.Status{StatusCode: -1, StatusMsg: "fail"}, Token: "", Uid: 0,
		})
	}

	err = db.Model(&dbregister{
		User: models.User{Uid: uid},
	}).Where("uid=?", uid).Update("token", token).Error
	if err != nil {
		ctx.JSON(http.StatusBadRequest, registermsg{
			Status: models.Status{StatusCode: -1, StatusMsg: "fail"}, Token: "", Uid: 0,
		})
		logrus.Error("更新token失败")
	}

	ctx.JSON(http.StatusOK, registermsg{
		Status: models.Status{
			StatusCode: 0,
			StatusMsg:  "success",
		},
		Token: token,
		Uid:   uid,
	})

}
